package cn.practice.articlepractice01.controller;

import cn.practice.articlepractice01.common.response.JsonResult;
import cn.practice.articlepractice01.common.response.StatusCode;
import cn.practice.articlepractice01.pojo.dto.UserArticleDTO;
import cn.practice.articlepractice01.pojo.dto.UserLoginDTO;
import cn.practice.articlepractice01.pojo.entity.Article;
import cn.practice.articlepractice01.pojo.mapper.UserMapper;
import cn.practice.articlepractice01.pojo.vo.ArticleVO;
import cn.practice.articlepractice01.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@Api(tags = "用户模块")
@RequestMapping("/v1/users/")
@Validated
public class UserController {
    @Autowired
    private UserMapper usermapper;
    @Autowired
    private HttpSession httpSession;

    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userLoginDTO" + userLoginDTO);

        UserVO userVO = usermapper.login(userLoginDTO);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.success();
    }

    @PostMapping("article")
    @ApiOperation(value = "发布文章")
    public JsonResult insert(@RequestBody @Validated UserArticleDTO userArticleDTO){
        log.debug("userArticle " + userArticleDTO);

        UserVO userVO = (UserVO) httpSession.getAttribute("user");

        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());

        usermapper.insertArticle(article);

        return JsonResult.success();
    }

    @GetMapping("selectByArticleId")
    @ApiOperation(value = "根据文章id查询文章")
    public JsonResult selectByArticleId(@RequestParam("articleId")
                                            @Range(min = 1,max = 200, message = "文章id在1到200之间")
                                            Integer articleId){
        log.debug("articleId " + articleId);

        ArticleVO articlevo = usermapper.selectByArticleId(articleId);

        return JsonResult.success(articlevo);
    }


}
